package com.yohann.algorithm;

/**
 * <p>
 * 数组模拟栈
 * </p>
 *
 * @author Yohann
 * @since 2020/9/23
 */
public class StackTest {
    public static void main(String[] args) {
        ArrayStack stack = new ArrayStack(3);
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.dispaly();
        System.out.println(stack.pop());
        stack.push(4);
        System.out.println(stack.pop());
        System.out.println(stack.pop());
    }
}

class ArrayStack{
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack(int maxSize){
        this.maxSize = maxSize;
        this.stack = new int[this.maxSize];
    }

    //栈满
    public boolean isFull(){
        return top == maxSize - 1;
    }

    //栈空
    public boolean isEmpty(){
        return top == -1;
    }

    //入栈
    public void push(int value){
        if (isFull()) {
            System.out.println("栈已满！");
            return;
        }

        stack[++top] = value;
    }

    //出栈
    public int pop(){
        if (isEmpty()) {
            throw new RuntimeException("栈已空！");
        }

        return stack[top--];
    }

    //遍历

    public void dispaly(){
        if (isEmpty()){
            System.out.println("栈已空！");
        }

        for (int i = top; i > -1; i--){
            System.out.print(stack[i]+" ");
        }
        System.out.println();
    }
}